<?php
/**
 * Created by PhpStorm.
 * User: Eric-pc3
 * Date: 2018/8/2
 * Time: 18:37
 */

namespace app\common\service;

use app\common\logic\ApiLogic;
use app\common\logic\ContentLogic;
use app\common\logic\SmsLogic;
use app\common\logic\SysLogic;
use GeTui\ApiException;
use getui\Getui;
use think\facade\Cache;
use think\facade\Log;

class SysService extends BaseService
{
    public function getSlidesByCategoryId($categoryId = 0,$topSize = 5){
        $cacheKey = 'SysService_getSlidesByCategoryId_' . $categoryId . '_' . $topSize;
        $dataList = Cache::tag('Content')->get($cacheKey);
        if (empty($dataList)) {
            $contentLogic = new ContentLogic();
            $where[] = ['model_id','=',5];
            if (!empty($categoryId)) {
                $where[] = ['category_id','=',$categoryId];
            }
            $dataList = $contentLogic->_getAllListByWhere($where,$topSize,'level DESC,id DESC',
                0,'Content');

            // 过滤数据
            $fanhui = [];
            foreach ($dataList as $item) {
                $fanhui[] = [
                    'title' => $item['title'],
                    'photo' => getPhotoCdnUrl($item['cover_url']),
                    'jump_url' => $item['jump_url'],
                ];
            }
            $dataList = $fanhui;

            Cache::tag('Content')->set($cacheKey,$dataList,600);
        }
        return $this->retSuccess('成功',$dataList);
    }

    /**
     * 发送司机审核消息
     * @param int $sendMemberId
     * @param int $receiveMemberId
     * @param boolean $pass 是否通过
     * @param array $memberAuthModel
     * @return array
     */
    public function sendMemberAuthMessage($receiveMemberId,$pass,$memberAuthModel){
        $title = '';
        $content = '';
        if ($pass) {
            $title = '司机认证通过';
            $content = '恭喜您认证通过了';
        }
        else{
            $title = '司机认证驳回';
            $content = '认证被驳回，驳回理由：' . $memberAuthModel['auth_remark'];
        }

        $sysLogic = new SysLogic();
        $jieguo = $sysLogic->_sendMessage(0, $receiveMemberId, $title, $content);
        if ($jieguo < 1) {
            return $this->retError(1, '发送失败');
        }
        else{
            try {
                // 发送APP推送
                $this->sendPushMessageByMemberId($receiveMemberId,$title,$content,[
                    'action' => 'msgView',
                    'data' => [
                        'id' => $jieguo
                    ],
                    'type' => 'member_auth',
                ]);
            } catch (\Exception $exception) {
                Log::error('sendMemberAuthMessage 发送司机审核 推送消息 失败');
            }

            return $this->retSuccess();
        }
    }

    /**
     * 发送车辆审核消息
     * @param int $sendMemberId
     * @param int $receiveMemberId
     * @param boolean $pass 是否通过
     * @param array $carModel
     * @return array
     */
    public function sendCarAuthMessage($receiveMemberId,$pass,$carModel){
        $title = '';
        $content = '';
        if ($pass) {
            $title = $carModel['car_no'] .' 车辆认证通过';
            $content = $carModel['car_no'] .' 恭喜您认证通过了';
        }
        else{
            $title = $carModel['car_no'] .' 车辆认证驳回';
            $content = $carModel['car_no'] . ' 认证被驳回，驳回理由：' . $carModel['auth_remark'];
        }

        $sysLogic = new SysLogic();
        $jieguo = $sysLogic->_sendMessage(0, $receiveMemberId, $title, $content);
        if ($jieguo < 1) {
            return $this->retError(1, '发送失败');
        }
        else{
            try {
                // 发送APP推送
                $this->sendPushMessageByMemberId($receiveMemberId,$title,$content,[
                    'action' => 'msgView',
                    'data' => [
                        'id' => $jieguo
                    ],
                    'type' => 'car_auth',
                ]);
            } catch (\Exception $exception) {
                Log::error('sendCarAuthMessage 发送车辆审核 推送消息 失败');
            }

            return $this->retSuccess();
        }
    }

    /**
     * 新的派单通知
     * @param array $carList 车列表
     * @return array
     */
    public function sendMemberNewOrderMessage(array $carList){
        $sysLogic = new SysLogic();
        foreach ($carList as $item) {
            $messageId = $sysLogic->_sendMessage(0, $item['member_id'],
                $item['car_no'] . ' 您有新的派单，敬请留意'
                , $item['car_no'] . ' 您有新的派单，下拉刷新首页查看最新订单情况');
            if ($messageId < 1) {
                Log::error(' sendMemberNewOrderMessage 派单消息发送失败 $item ' .
                    json_encode($item, 256));
            }

            try {
                // 查询出手机号
                $smsLogic = new SmsLogic(getProjectId());
                $phone = $smsLogic->_getValue([
                    ['delete_time','<',1],
                    ['id','=',$item['member_id']],
                ],'mobile','Member');
                // 发送短信通知
                $smsLogic->sendNewOrderMessage($phone, $item['car_no']);
            } catch (\Exception $exception) {
                Log::error('sendMemberNewOrderMessage 发送新订单短信失败 ' . json_encode($item, 256));
            }

            try {
                // 发送APP推送
                $this->sendPushNewOrderMessageByCarModel($item, $messageId);
            } catch (\Exception $exception) {
                Log::error('sendMemberNewOrderMessage 发送新订单推送消息失败 ' . json_encode($item, 256));
            }
        }
    }

    /**
     * 获取我的消息，分页，带分页信息
     * @param $memberId
     * @param $pageIndex
     * @param int $pageSize
     * @return array
     */
    public function getMyMessagePager($memberId,$pageIndex,$pageSize = 20){
        $sysLogic = new SysLogic();
        $count = $sysLogic->_getMyMessageCount($memberId);
        $dataList = $sysLogic->_getMyMessagePager($memberId, $pageIndex, $pageSize);
        return $this->retSuccess('成功',[
            'has_more' => $this->_getHasMorePage($count,$pageIndex,$pageSize),
            'pageInfo' => [
                'row_count' => $count,
                'page_count' => ceil($count / $pageSize),
                'page_index' => $pageIndex,
                'page_size' => $pageSize,
            ],
            'list' => $dataList,
        ]);
    }

    /**
     * 获取我的某条消息
     * @param $memberId
     * @param $messageId
     * @param bool $setRead 是否设置已读
     * @return array
     */
    public function getMyMessageModel($memberId,$messageId,$setRead = false){
        $sysLogic = new SysLogic();
        $model = $sysLogic->_getMyMessage($memberId, $messageId);
        if (empty($model)) {
            return $this->retError(1, '找不到消息');
        }
        else{
            if (!empty($setRead)) {
                $this->readMyMessage($memberId, $messageId);
            }
            return $this->retSuccess('成功',$model);
        }
    }

    /**
     * 消息 设置为已读
     * @param $memberId
     * @param $messageId
     * @return array
     */
    public function readMyMessage($memberId,$messageId){
        $sysLogic = new SysLogic();
        $jieguo = $sysLogic->_readMyMessage($memberId, $messageId);
        if (false === $jieguo) {
            return $this->retError(1, '已读失败');
        }
        else{
            return $this->retSuccess();
        }
    }

    /**
     * 删除消息
     * @param $memberId
     * @param $messageId
     * @return array
     */
    public function delMyMessage($memberId,$messageId){
        $sysLogic = new SysLogic();
        $jieguo = $sysLogic->_delMyMessage($memberId, $messageId);
        if (false === $jieguo) {
            return $this->retError(1, '删除失败');
        }
        else{
            return $this->retSuccess();
        }
    }
    public function getFreightModelById($id){
        $where[] = ['id','=',$id] ;
        return $this->getFreightModel($where);
    }
    public function getFreightModel($where){
        $sysLogic = new SysLogic();
        $where[] = ['delete_time','<',1] ;
        $model = $sysLogic->_getModelByOriginalWhere($where, 'Freight');
        if (empty($model)) {
            return $this->retError(1, '找不到数据');
        }
        else{
            return $this->retSuccess('成功', $model);
        }
    }

    public function getFreightList(){
        $sysLogic = new SysLogic();

        $dataList = $sysLogic->_getAllListByWhere([], 0, '', 0, 'Freight');

        return $this->retSuccess('成功', $dataList);
    }

    public function getCargoModelById($id){
        $where[] = ['id','=',$id] ;
        return $this->getCargoModel($where);
    }
    public function getCargoModel($where){
        $sysLogic = new SysLogic();
        $where[] = ['delete_time','<',1] ;
        $model = $sysLogic->_getModelByOriginalWhere($where, 'Cargo');
        if (empty($model)) {
            return $this->retError(1, '找不到数据');
        }
        else{
            return $this->retSuccess('成功', $model);
        }
    }

    /**
     * 发送APP推送 新订单 消息
     * @param array $carModel
     * @param int $messageId
     * @return array
     */
    public function sendPushNewOrderMessageByCarModel(array $carModel,$messageId = 0){
        if (empty($carModel)) {
            return $this->retError(1, '$carModel 不能为空');
        }

        if ($messageId > 0) {
            $payload = [
                'action' => 'msgView',
                'data' => [
                    'id' => $messageId
                ],
                'type' => 'new_order',
            ];
        }
        else{
            $payload = [];
        }

        return $this->sendPushMessageByMemberId($carModel['member_id'],
            $carModel['car_no'] . '有新的派单',
            '请登录APP下拉刷新首页查看详情',
            $payload
        );
    }

    public function sendPushMessageByMemberId($memberId,$title, $message, $payload){
        $apiLogic = new ApiLogic();
        $userTokenModel = $apiLogic->_getLastUserTokenByUserId($memberId);
        if (empty($userTokenModel)) {
            return $this->retError(1, '未找到设备');
        }

        $jieguo = $this->_sendPushMessage(strtolower($userTokenModel['system_os']),$userTokenModel['push_client_id'],
            $title,
            $message,
            $payload
        );

        if (false === $jieguo) {
            return $this->retError(1, '推送消息失败');
        }
        else{
            return $this->retSuccess('推送消息成功');
        }
    }

    public function _sendPushMessage($osName,$clientId,$title, $message, $payload)
    {
        try {
            $client = new \GeTui\Client([
                'app_key' => 'SWAx2avkjH7IPJcxnp49o6',
                'app_id' => '1viDZMI3gZ8dUWRly1cin5',
                'master_secret' => 'tc3Yed9yDr5ahoeuF3wJu3',
                'logo_url' => '',
//                'logo_url' => 'http://dev.img.ybzg.com/static/app/user/getui_logo.png',
            ]);
            $jieguo = ['result' => false];
            if (empty($osName) || 'ios' == $osName) {
                $ret = $client->single->setClientId($clientId)
                    ->setNotification(function (\GeTui\Template\Notification $notification)
                    use ($payload) {
                        /** (安卓有效)收到消息是否立即启动应用，true为立即启动，false则广播等待启动，默认是否 */
                        $notification->setTransmissionType(true);
                        /** 设置透传的内容 */
                        if (!empty($payload)) {
                            //自定义透传内容
                            $notification->setTransmissionContent(json_encode($payload));
                        }
                        /** 设定展示开始时间，格式为yyyy-MM-dd HH:mm:ss */
//                    $notification->setDurationBegin();
                        /** 设定展示结束时间，格式为yyyy-MM-dd HH:mm:ss */
//                    $notification->setDurationBegin();
                    })
                    ->setPushInfo(function (\GeTui\Template\PushInfo $pushInfo)
                    use ($title, $message,$payload){
                        //（必传）通知标题
                        $pushInfo->setTitle($title);
                        //（必传）通知内容
                        $pushInfo->setBody($message);
                        if (!empty($payload)) {
                            //自定义透传内容
                            $pushInfo->setPayload(json_encode($payload));
                        }
                        //推送直接带有透传数据 默认1，可选-1
                        $pushInfo->setContentAvailable(1);
                        //用于计算icon上显示的数字，还可以实现显示数字的自动增减，如“+1”、 “-1”、 “1” 等，计算结果将覆盖badge，默认是+1
                        $pushInfo->setAutoBadge('+1');
                        //通知铃声文件名，无声设置为“com.gexin.ios.silence”，默认default
                        $pushInfo->setSound('default');

                        //多媒体设置
                        //资源类型（1.图片，2.音频， 3.视频）
//                    $pushInfo->setType(1);
                        //是否只在wifi环境下加载，如果设置成true,但未使用wifi时，会展示成普通通知，默认是false
//                    $pushInfo->setOnlyWifi(false);
                        //多媒体资源地址
//                    $pushInfo->setUrl('');
                    })
                    ->push();
//                var_dump($ret);
                $jieguo = $ret;
            }

            if (empty($osName) || 'android' == $osName) {
                $client->single->setClientId($clientId)
                    ->setStyle(function (\GeTui\Template\Style $style)
                    use ($title,$message){
                        /** 设置标题（必传） */
                        $style->setTitle($title);
                        /** 设置内容（必传） */
                        $style->setText($message);

                        /** 通知是否可清除： true可清除，false不可清除。默认可清除 */
                        $style->setIsClearable(true);
                        /** 收到通知是否振动：true振动，false不振动。默认振动 */
                        $style->setIsVibrate(true);
                        /** 收到通知是否响铃：true响铃，false不响铃。默认响铃 */
                        $style->setIsRing(true);

                        /** 展开通知样式，设置类型
                         * 1 通知展示大图样式，参数是大图的URL地址
                         * 2 通知展示文本+长文本样式，参数是长文本
                         * 3 通知展示大图+小图样式，参数是大图URL和小图URL
                         */
                        $style->setBigStyle(2);
                        $style->setBigText($message);

                    });
                $client->single->setNotification(function (\GeTui\Template\Notification $notification)
                use ($client,$payload) {
                    //收到消息是否立即启动应用，true为立即启动，false则广播等待启动，默认是否
                    $notification->setTransmissionType(true);
                    if (!empty($payload)) {
                        //（可空）透传字符串
                        $notification->setTransmissionContent(json_encode($payload));
                    }

                    //（必传）设置样式，结合Style的设置获取指定的样式类型：system(个推),getui(个推),banner(背景图),expand(展开)
                    $notification->setStyle($client->single->getStyle());
                    //设定展示开始时间，格式为yyyy-MM-dd HH:mm:ss
//                    $notification->setDurationBegin('2018-05-06 12:00:00');
                    //设定展示结束时间，格式为yyyy-MM-dd HH:mm:ss
//                    $notification->setDurationEnd('2018-05-08 12:00:00');
                });
                $ret = $client->single->push();
//                var_dump($ret);
                $jieguo = $ret;
            }
            return $jieguo['result'] == 'ok';
        } catch (ApiException $e) {
            Log::error('个推发送推送消息失败 ' . $e->getMessage().
                ' LINE ' . $e->getLine() . ' FILE ' . $e->getFile()
            );

            return false;
        }
    }
}